package io.renren.modules.generator.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.renren.modules.sys.entity.SysCaptchaEntity;
import io.renren.modules.sys.entity.SysLogEntity;
import io.renren.modules.sys.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.generator.dao.DataLogDao;
import io.renren.modules.generator.entity.DataLogEntity;
import io.renren.modules.generator.service.DataLogService;
import org.springframework.core.io.ResourceLoader;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@Service("dataLogService")
public class DataLogServiceImpl extends ServiceImpl<DataLogDao, DataLogEntity> implements DataLogService {

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private SysLogService sysLogService;

    @Override
    public void analysis() {
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        // 组装数据
        List<List<String>> dataLogEntities = new ArrayList<>();
        try {
            Resource resource = resourceLoader.getResource("classpath:file/1127.txt");
            is = resource.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String data = null;
            while((data = br.readLine()) != null) {
                List<String> list = Arrays.asList(data.split(","));
                dataLogEntities.add(list);
            }
            this.baseMapper.analysisBatch(dataLogEntities);

        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            try {
                br.close();
                isr.close();
                is.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<DataLogEntity> top(String startTime, String endTime) {
        // 使用sql语句查询获得time处于2022/9/24 9:40到2022/9/24 10:20之间的数据，并在此基础上查询显示ID频次最高的数据记录。
        List<DataLogEntity> topList = this.list();
        if(CollUtil.isNotEmpty(topList)){
            List<String> collect = topList.stream().filter(bean -> bean.getTime().compareToIgnoreCase(startTime) >= 0)
                    .filter(bean -> bean.getTime().compareToIgnoreCase(endTime) <= 0).map(bean -> bean.getDataId()).collect(Collectors.toList());
            log.info("collect value is {}",collect);
            // 版本V1.0
            Object ss = collect.stream()
                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                    .entrySet()
                    .stream()
                    .max(Map.Entry.comparingByValue())
                    .map(Map.Entry::getKey)
                    .orElse(null);
            log.info("次数最高的为：{}",ss);
            return topList.stream().filter(bean -> bean.getDataId().contains(String.valueOf(ss))).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<DataLogEntity> page = this.page(
                new Query<DataLogEntity>().getPage(params),
                new QueryWrapper<DataLogEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 测试事务处理
     */
    @Override
    public void testTrancation() {
        log.info("测试事务处理");
        this.sysLogService.saveAdd(SysLogEntity.builder().ip("123").time(999L).method("A").operation("11").params("1").username("uname").build());
        // this.saveAdd(SysLogEntity.builder().ip("123").time(999L).method("A").operation("11").params("1").username("uname").build());
        int a = 1/0;
        log.info("a value is {}",a);
    }

//    @Transactional(rollbackFor = Exception.class)
//    public boolean saveAdd(SysLogEntity sysLogEntity) {
//        // int a = 1/0;
//        return this.sysLogService.save(sysLogEntity);
//    }
}